package com.hna.cums.web.AnlyCtl;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooDefs.Ids;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSONObject;
@Controller
public class ZkApiCtx {
	static final Logger logger = LoggerFactory.getLogger(AnlyMainCtl.class);
	private String sessionid;
	JSONObject resultObj = new JSONObject();
	protected String hosts = "node1:2181,node2:2181";  
    /** 
     * 连接的超时时间, 毫秒 
     */  
    private static final int SESSION_TIMEOUT = 5000;  
	@RequestMapping("ZookerTest.do")
	public String AnlyTest(HttpServletRequest request, HttpServletResponse response) {
		try {
			ZooKeeper zk = new ZooKeeper(hosts, SESSION_TIMEOUT, new Watcher(){

				@Override
				public void process(WatchedEvent evt) {
					// TODO Auto-generated method stub
					logger.info("已经触发了" + evt.getType() + "事件！");
					if(evt.getType() == Watcher.Event.EventType.NodeDataChanged){
						logger.info("new data" );
					}
					
				}
				
			});
			
			Stat st = zk.exists("/lele", false);
			if(st == null){
				logger.debug("file not exists");
				zk.create("/lele", "testRootData".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); 
			}
			Stat ret = new Stat();
			zk.getChildren("/lele", false, ret);
			//logger.debug("run : " + ret.getVersion());
			
			String StrRet = new String(zk.getData("/lele", false, ret));
			logger.debug("now data is: " + StrRet);
			int version = ret.getVersion();
			logger.debug("getVersion data is: " + version);
			zk.setData("/lele", "hahahha".getBytes(), version + 1);
			logger.debug("run complete: " + StrRet);
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (KeeperException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;		
	}
	
}
